import React, {useState} from 'react';
import {Table, Input, Button, Form, Select} from 'antd';

const {Option} = Select;

export default function Topic2_2() {
  const [form] = Form.useForm();
  const msgData = {
    "code": 0,
    "data": {
      "models": [
        {
          "id": 1,
          "sceneName": "场景01)",
          "city": "要求：1.xxxxxxxxxxxxxxx; 2.xxxxxxxxxxxxxxx; 3.xxxxxxxxxxxxxxx; 4.xxxxxxxxxxxxxxx",
          "creator": "somebody",
          "modifier": "somebody",
          "createTime": "2020-03-11 11:05:35",
          "modifyTime": "2020-03-18 21:48:11",
          "url": "http://www.baidu.com",

        },
        {
          "id": 2,
          "sceneName": "场景02)",
          "city": "要求：1.xxxxxxxxxxxxxxx; 2.xxxxxxxxxxxxxxx; 3.xxxxxxxxxxxxxxx; 4.xxxxxxxxxxxxxxx",
          "creator": "somebody",
          "modifier": null,
          "createTime": "2020-03-11 11:05:44",
          "url": "http://www.google.com",
          "modifyTime": "2020-03-11 11:05:44",
        },

      ],
      "total": 37
    },
    "message": "success"
  }
  const setDataKey = () => {
    msgData.data.models.forEach((elm, index) => {
      elm.key = elm.id;
    })
  }
  setDataKey()
  const [data, setData] = useState(msgData.data.models);
  const add = (record) => {
    console.log(record.id)
    const newData = [...data];
    const index = newData.findIndex((item) => record.id === item.id);
    console.log(index)
    newData[index].roles.push({
      role: '123',
      parentId: record.id,
      key: +new Date(),
      quantity: '123'
    })
    console.log(newData[index].roles)
    setData(newData);
  }
  const handleChange = (value, record, index) => {
    // console.log(`selected ${value}`);
    const newData = [...data];
    const _index = newData.findIndex((item) => record.parentId === item.id);
    console.log({value, record, index, _index, newData})

    newData[_index].roles[index].role = value
    // newData[_index][index].role = value
    setData(newData);
  }
  const columnsChildren = [
    {
      title: '设备角色',
      dataIndex: 'role',
      width: '10%',
      render: (_, record, index) => {
        return (
          <Select defaultValue={record.role} style={{width: 120}}
                  onChange={(value) => handleChange(value, record, index)}>
            <Option key={'jack'} value="jack">张三</Option>
            <Option key={'lucy'} value="lucy">李四</Option>
            <Option key={'john'} value="john">王五</Option>
          </Select>
        )
      }
      // editable: true,
    },
    {
      title: '设备数量',
      dataIndex: 'quantity',
      width: '10%',
      // editable: true,
    },
  ]
  const mergedColumnsChildren = columnsChildren.map((col) => {
    if (!col.editable) {
      return col;
    }
    console.log(col)
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        // editing: isEditing(record),
      }),
    };
  });

  const columns = [
    {
      title: '场景名称',
      dataIndex: 'sceneName',
      width: '10%',
      editable: true,
      render: (_, record) => {
        return (
          <Button target="_blank" href={record.url} type="link">{record.sceneName}</Button>
        )
      }
    },
    {
      title: '城市',
      dataIndex: 'city',
      width: '10%',
    },
    {
      title: '角色·设备数量',
      dataIndex: 'roles',
      width: '10%',
      render: (_, record) => {
        record.roles = record.roles || [{
          role: '123',
          key: 1,
          parentId: record.id,
          quantity: '123'
        }]
        return (
          <Form key={+new Date()} form={form} component={false}>
            <Table
              pagination={false}
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              dataSource={record.roles}
              columns={mergedColumnsChildren}
              rowClassName="editable-row"
            />
            <Button onClick={() => add(record)}>新增角色</Button>
          </Form>
        )
      }
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        // dataIndex: col.dataIndex,
        title: col.title,
        // editing: isEditing(record),
      }),
    };
  });
  const EditableCell = ({
                          editing,
                          dataIndex,
                          title,
                          inputType,
                          record,
                          index,
                          children,
                          ...restProps
                        }) => {
    return (
      <td key={index} {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            <Input/>
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  return (
    <Table
      bordered
      pagination={false}
      dataSource={data}
      columns={mergedColumns}
      rowClassName="editable-row"
    />
  )
}
